const fs = require('fs');
const path = require('path');
const { program } = require('commander');

const apng2png = require('./lib/apng2png');
const { version } = require('./package.json');

program
    .version(version)
    .option('-p, --path <path>', 'file path')
    .option('-o, --output <path>', '[可选]: output dir')
    .parse(process.argv);

let filePath = program.path;
if (!filePath) {
    console.log('path is undefined');
    process.exit(0);
} else {
    filePath = path.resolve(filePath);
}

if (!fs.existsSync(filePath)) {
    console.log(`<path error> no such file or directory: ${filePath}`);
    process.exit(0);
}

let outputDir = program.output;
if (!outputDir) {
    outputDir = path.resolve('./');
} else if (!fs.existsSync(outputDir)) {
    console.log(`<output error> no such file or directory: ${outputDir}`);
    process.exit(0);
}

apng2png(filePath, outputDir)
    .then(({ css, filename }) => {
        console.log(`生成成功: 文件名 > ${filename}\n\ncss:\n${css}`);
        process.exit(0);
    })
    .catch(err => {
        console.log(err);
        process.exit(0);
    });

process.on('uncaughtException', err => {
    console.log(err);
    process.exit(0);
});

process.on('unhandledRejection', err => {
    console.log(err);
    process.exit(0);
});
